package com.minsu.service.impl;

import com.minsu.dto.LoginRequest;
import com.minsu.dto.LoginResponse;
import com.minsu.entity.SysUser;
import com.minsu.service.AuthService;
import com.minsu.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    private final AuthenticationManager authenticationManager;
    private final SysUserService userService;

    public AuthServiceImpl(AuthenticationManager authenticationManager, SysUserService userService) {
        this.authenticationManager = authenticationManager;
        this.userService = userService;
    }

    @Override
    public LoginResponse login(LoginRequest request) {
        try {
            log.info("用户尝试登录: {}", request.getUsername());
            
            // 检查用户是否存在
            SysUser user = userService.findByUsername(request.getUsername());
            if (user == null) {
                log.warn("登录失败：用户不存在 - {}", request.getUsername());
                return LoginResponse.error("用户不存在");
            }

            // 创建认证token
            UsernamePasswordAuthenticationToken authToken = 
                new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword());
            
            // 进行认证
            Authentication authentication = authenticationManager.authenticate(authToken);
            
            // 认证成功，设置认证信息到上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // 生成token（这里简单使用session id，实际项目中可能使用JWT）
            String token = authentication.getName() + "_" + System.currentTimeMillis();
            
            log.info("用户登录成功: {}", request.getUsername());
            return LoginResponse.success(user.getUsername(), user.getNickname(), token);
            
        } catch (BadCredentialsException e) {
            log.warn("登录失败：密码错误 - {}", request.getUsername());
            return LoginResponse.error("用户名或密码错误");
        } catch (Exception e) {
            log.error("登录异常: {} - {}", request.getUsername(), e.getMessage(), e);
            return LoginResponse.error("登录失败：" + e.getMessage());
        }
    }

    @Override
    public SysUser getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            return userService.findByUsername(userDetails.getUsername());
        }
        return null;
    }

    @Override
    public void logout() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            log.info("用户退出登录: {}", auth.getName());
        }
        SecurityContextHolder.clearContext();
    }
} 